/**
 * Copyright &copy; 2012-2016 <a href="https://github.com/thinkgem/jeesite">JeeSite</a> All rights reserved.
 */
package com.thinkgem.jeesite.modules.teach.web;

import com.google.gson.Gson;
import com.thinkgem.jeesite.common.ConstantEnum;
import com.thinkgem.jeesite.common.config.Global;
import com.thinkgem.jeesite.common.mapper.JsonMapper;
import com.thinkgem.jeesite.common.persistence.Page;
import com.thinkgem.jeesite.common.persistence.ReturnObject;
import com.thinkgem.jeesite.common.service.CrudService;
import com.thinkgem.jeesite.common.utils.DateUtils;
import com.thinkgem.jeesite.common.utils.StringUtils;
import com.thinkgem.jeesite.common.utils.excel.ExportExcel;
import com.thinkgem.jeesite.common.web.ExcelController;
import com.thinkgem.jeesite.modules.act.entity.Act;
import com.thinkgem.jeesite.modules.act.utils.ActUtils;
import com.thinkgem.jeesite.modules.sys.dao.MenuDao;
import com.thinkgem.jeesite.modules.sys.entity.Dict;
import com.thinkgem.jeesite.modules.sys.security.FormAuthenticationFilter;
import com.thinkgem.jeesite.modules.sys.service.SystemService;
import com.thinkgem.jeesite.modules.sys.utils.DictUtils;
import com.thinkgem.jeesite.modules.sys.utils.UserUtils;
import com.thinkgem.jeesite.modules.teach.entity.CalculationUtils;
import com.thinkgem.jeesite.modules.teach.entity.TpTeachActive;
import com.thinkgem.jeesite.modules.teach.service.TpTeachActiveService;
import org.apache.commons.lang3.StringEscapeUtils;
import org.apache.shiro.authz.annotation.RequiresPermissions;
import org.apache.shiro.web.util.WebUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.servlet.mvc.support.RedirectAttributes;

import javax.script.ScriptException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * 教学活动表Controller
 * @author 康力
 * @version 2018-03-12
 */
@Controller
@RequestMapping(value = "${adminPath}/teach/tpTeachActive")
public class TpTeachActiveController extends ExcelController<TpTeachActive> {

	@Autowired
	private TpTeachActiveService tpTeachActiveService;

	@Autowired
	private SystemService systemService;

	@Autowired
	private MenuDao menuDao;

	private String defaultStr="/teach/tpTeachActive/";

	@ModelAttribute
	public TpTeachActive get(@RequestParam(required=false) String id) {
		TpTeachActive entity = null;
		if (StringUtils.isNotBlank(id)){
			entity = tpTeachActiveService.get(id);
		}
		if (entity == null){
			entity = new TpTeachActive();
		}
		//根据拥有当前菜单角色的最大的数据范围 判断是否是获取本人数据
		entity.setUserDataScope(systemService.getCurUserDataScopeByPermission("teach:tpTeachActive:view"));
		if (entity.getIsNewRecord() && entity.getUserDataScope() == 0) {// 个人数据权限，获取个人信息
			entity.setUser(UserUtils.getUser());// 设置人员
			if (entity.getUser() != null) {
				entity.setDepartment(entity.getUser().getOffice());// 设置科室
				if (entity.getDepartment() != null) {
					// 设置教研室
					entity.setTrc(systemService.findParentByOfficeId(entity.getDepartment().getId()));
				}
			}
		}
		return entity;
	}
	
	@RequiresPermissions("teach:tpTeachActive:view")
	@RequestMapping(value = {"list", ""})
	public String list(TpTeachActive tpTeachActive, HttpServletRequest request, HttpServletResponse response, Model model) {
		String str = request.getRequestURI().replaceFirst(request.getContextPath()+Global.getConfig("adminPath"), "")+"?teachTypes="+tpTeachActive.getTeachTypes();
		model.addAttribute("remark",systemService.getRemark(str));
		//根据拥有当前菜单角色的最大的数据范围 判断是否是获取本人数据
		tpTeachActive.setUserDataScope(systemService.getCurUserDataScopeByPermission("teach:tpTeachActive:view"));
		if(tpTeachActive.getUserDataScope() == 0){
			tpTeachActive.setUser(UserUtils.getUser());
		}else{//获得当前登录人部门下的数据
			if(tpTeachActive.getDepartment() == null){
				tpTeachActive.setDepartment(UserUtils.getUser().getOffice());
			}
		}
		Page<TpTeachActive> page = tpTeachActiveService.findPage(new Page<TpTeachActive>(request, response), tpTeachActive);
		if(WebUtils.isTrue(request, FormAuthenticationFilter.DEFAULT_MOBILE_PARAM)){//移动端请求，封装数据
			ReturnObject rtobj = new ReturnObject();
			rtobj.setResult(ConstantEnum.success.getCode());
			rtobj.setMsg(ConstantEnum.success.getName());
			rtobj.setData(page);
			return renderString(response, rtobj);
		}
//		getCustomTitle(model,tpTeachActive.getTeachTypes());
		model.addAttribute("teachTypes",tpTeachActive.getTeachTypes());
		model.addAttribute("page", page);
		return "modules/teach/tpTeachActiveList";
	}

	@RequiresPermissions("teach:tpTeachActive:view")
	@RequestMapping(value = "form")
	public String form(TpTeachActive tpTeachActive, Model model, HttpServletRequest request, HttpServletResponse response) {
		//如果为新增数据并且数据权限为个人数据的情况下，启动审批流程
		String viewName = "";
		if(tpTeachActive == null ||
			(tpTeachActive.getStatus()!= null && tpTeachActive.getStatus() == 2)||
			(StringUtils.isBlank(tpTeachActive.getId())&&StringUtils.isBlank(tpTeachActive.getAct().getProcInsId()))){
			//根据流程名称获取最新的流程实例名称
			String procDefId = null;
			if(systemService.getCurUserDataScopeByPermission("teach:tpTeachActive:view") == 0){
				//不同的教学活动类型需要走不同的审核流程
				String proDefKey=null;
				if(StringUtils.isNoneEmpty(tpTeachActive.getTeachType())){
					if(ActUtils.TEACH_ACTIVE_TYPE_DEPT.indexOf(tpTeachActive.getTeachType())>=0){
						proDefKey =  ActUtils.TP_TEACH_ACTIVE_DEPT[0];
					}else if(ActUtils.TEACH_ACTIVE_TYPE_JYS.indexOf(tpTeachActive.getTeachType())>=0){
						proDefKey =  ActUtils.TP_TEACH_ACTIVE_JYS[0];
					}
				}
				if(proDefKey == null)proDefKey =  ActUtils.TP_TEACH_ACTIVE_ADMIN[0];
				procDefId =  systemService.getprocDefIdByProcDefKey(proDefKey);
			}
			Act act = new Act();
			act.setProcDefId(procDefId);
			tpTeachActive.setAct(act);
			viewName="tpTeachActiveForm";
		} else if (tpTeachActive.getAct() != null && tpTeachActive.getAct().getTaskDefKey() != null
				&& tpTeachActive.getAct().getTaskDefKey().startsWith("audit")
				&&tpTeachActive.getAct().isTodoTask()) {
			viewName="tpTeachActiveAudit";
		}else{
			viewName="tpTeachActiveView";
			//如果实体类内容未查出，使用ProcInsId查询
			Act act = tpTeachActive.getAct();
			if(StringUtils.isBlank(tpTeachActive.getId()) && act != null
					&& StringUtils.isNotBlank(act.getProcInsId())){
				tpTeachActive.setProcInsId(act.getProcInsId());
				List<TpTeachActive> list = tpTeachActiveService.findList(tpTeachActive);
				if(list.size() == 1){
					tpTeachActive = list.get(0);
					tpTeachActive.setAct(act);
				}
			}
		}
		if(WebUtils.isTrue(request, FormAuthenticationFilter.DEFAULT_MOBILE_PARAM)){//移动端请求，封装数据
			ReturnObject rtobj = new ReturnObject();
			rtobj.setResult(ConstantEnum.success.getCode());
			rtobj.setMsg(ConstantEnum.success.getName());
			ExportExcel ex = new ExportExcel("", TpTeachActive.class);
			tpTeachActive = ex.getMobileDataList(tpTeachActive);
			tpTeachActive.setPropertyNameMap(ex.getPropertyNameMap());
			rtobj.setData(tpTeachActive);
			return renderString(response, rtobj);
		}
//		getCustomTitle(model,tpTeachActive.getTeachTypes());
		model.addAttribute("teachTypes",tpTeachActive.getTeachTypes());
		model.addAttribute("tpTeachActive", tpTeachActive);
		return "modules/teach/"+viewName;
	}

	@RequiresPermissions("teach:tpTeachActive:edit")
	@RequestMapping(value = "async_save")
	@ResponseBody
	public Object save(TpTeachActive tpTeachActive, Model model,
					   String startTime,String endTime,
					   HttpServletRequest request, HttpServletResponse response) {
		Map maps =DictUtils.getRemarkMapper("teach_type",tpTeachActive.getTeachType());
		String pattern = maps.containsKey("dateForma") ? String.valueOf(maps.get("dateForma")):"yyyy-MM-dd HH:mm";
		SimpleDateFormat sdf = new SimpleDateFormat(pattern);
		try {
			tpTeachActive.setStartTime(sdf.parse(startTime));
			tpTeachActive.setEndTime(sdf.parse(endTime));
		} catch (ParseException e1) {
			// TODO Auto-generated catch block
			e1.printStackTrace();
		}
		Long l=tpTeachActive.getEndTime().getTime()-tpTeachActive.getStartTime().getTime();
		String formula=maps.get("accountingFormula").toString().replaceAll("X",String.valueOf(l));
		try {
			if(tpTeachActive.getStuNum() == null && tpTeachActive.getScore() == null){
				Double stuNum= CalculationUtils.logicOperation(formula);
				tpTeachActive.setStuNum(stuNum);
				tpTeachActive.setScore(CalculationUtils.logicOperation(maps.get("workLoadFormula").toString().replaceAll("X",String.valueOf(stuNum))));
			}
		} catch (ScriptException e) {
			e.printStackTrace();
		}
		if (!beanValidator(model, tpTeachActive)){
			return form(tpTeachActive, model,request,response);
		}
		int rtn = tpTeachActiveService.saves(tpTeachActive);
		HashMap map=new HashMap();
		map.put("code",500);
		if(rtn>0){
			map.put("code",200);
			map.put("id",tpTeachActive.getId());
		}
		return map;
	}

	@RequiresPermissions("teach:tpTeachActive:edit")
	@RequestMapping(value = "save")
	public String save(TpTeachActive tpTeachActive, Model model, RedirectAttributes redirectAttributes,
			String startTime,String endTime,
			HttpServletRequest request, HttpServletResponse response) {
		Map maps =DictUtils.getRemarkMapper("teach_type",tpTeachActive.getTeachType());
		String pattern = (maps != null && maps.containsKey("dateForma")) ? String.valueOf(maps.get("dateForma")):"yyyy-MM-dd HH:mm";
		SimpleDateFormat sdf = new SimpleDateFormat(pattern);
		try {
			if(StringUtils.isNotBlank(startTime) && StringUtils.isNotBlank(endTime)){
				tpTeachActive.setStartTime(sdf.parse(startTime));
				tpTeachActive.setEndTime(sdf.parse(endTime));
			}
			if(tpTeachActive.getStuNum() == null && tpTeachActive.getEndTime() != null){
				Long l=tpTeachActive.getEndTime().getTime()-tpTeachActive.getStartTime().getTime();
				String formula=maps.get("accountingFormula").toString().replaceAll("X",String.valueOf(l));
				Double stuNum= CalculationUtils.logicOperation(formula);
				tpTeachActive.setStuNum(stuNum);
			}
			if(tpTeachActive.getStuNum()!=null && tpTeachActive.getScore() == null){
				tpTeachActive.setScore(CalculationUtils.logicOperation(maps.get("workLoadFormula").toString().replaceAll("X",String.valueOf(tpTeachActive.getStuNum()))));
			}
		} catch (ScriptException e) {
			e.printStackTrace();
		}catch (ParseException e1) {
			// TODO Auto-generated catch block
			e1.printStackTrace();
		}
		if (!beanValidator(model, tpTeachActive)){
			return form(tpTeachActive, model,request,response);
		}
		int rtn = tpTeachActiveService.saves(tpTeachActive);
		if(rtn>0)addMessage(redirectAttributes, "保存教学活动表成功");
		else addMessage(redirectAttributes,"保存失败：数据已存在");
		redirectAttributes.addAttribute("teachTypes", tpTeachActive.getTeachTypes());
		redirectAttributes.addAllAttributes(request.getParameterMap());
		return "redirect:"+Global.getAdminPath()+"/teach/tpTeachActive/?repage";
	}
	
	@RequiresPermissions("teach:tpTeachActive:edit")
	@RequestMapping(value = "delete")
	public String delete(TpTeachActive tpTeachActive, RedirectAttributes redirectAttributes,Model model) {
		tpTeachActiveService.delete(tpTeachActive);
		addMessage(redirectAttributes, "删除教学活动表成功");
		redirectAttributes.addAttribute("teachTypes",tpTeachActive.getTeachTypes());
		return "redirect:"+Global.getAdminPath()+"/teach/tpTeachActive/?repage";
	}
	@Override
	public String batchDelete(@RequestParam("idArr") List<String> idArr, TpTeachActive t, RedirectAttributes redirectAttributes) {
		redirectAttributes.addAttribute("teachTypes", t.getTeachTypes());
		return super.batchDelete(idArr, t, redirectAttributes);
	}
	@Override
	public String getTitle() {
		return "教学活动";
	}

	@Override
	public String defaultStr() {
		return defaultStr;
	}

	@Override
	public CrudService baseService() {
		return tpTeachActiveService;
	}
	@Override
	@RequiresPermissions("teach:tpTeachAchievement:view")
	@RequestMapping(value = "import/template")
	public String importFileTemplate(HttpServletResponse response, RedirectAttributes redirectAttributes,TpTeachActive data) {
		return super.importFileTemplate(response,redirectAttributes,data);
	}

	@RequiresPermissions("teach:tpTeachAchievement:edit")
	@RequestMapping(value = "import", method= RequestMethod.POST)
	public String importFile(MultipartFile file, RedirectAttributes redirectAttributes, TpTeachActive data,HttpServletRequest request) {
//		defaultStr+="?teachTypes="+data.getTeachTypes();
		redirectAttributes.addAllAttributes(request.getParameterMap());
		redirectAttributes.addAttribute("teachTypes", data.getTeachTypes());
		return super.importFile(file,redirectAttributes,data);
	}

	@Override
	@RequiresPermissions("teach:tpTeachAchievement:view")
	@RequestMapping(value = "export", method=RequestMethod.POST)
	public String exportFile(TpTeachActive data, HttpServletRequest request, HttpServletResponse response, RedirectAttributes redirectAttributes) {
		return super.exportFile(data,request,response,redirectAttributes);
	}

	@Override
	protected TpTeachActiveService getService() {
		return this.tpTeachActiveService;
	}
	/**
	 * 按类型统计出一段时间内每个科室的开展的某个或某些教学活动的学时或次数
	 * @param tpTeachActive
	 * @param request
	 * @param response
	 * @return
	 * @throws Exception
	 */
	@RequestMapping(value = "/statisticTeachType")
	public String statisticTeachType(TpTeachActive tpTeachActive, HttpServletRequest request, HttpServletResponse response) throws Exception {
		List<Dict> dicts = DictUtils.getDictListByIds("teach_type", tpTeachActive.getTeachTypeValues());
		//深度复制查询出的字典数据，防止后边修改list时，也同时修改了缓存中的数据
		List<Dict> teachTypes = DictUtils.deepCopyCollectionBySerialize(dicts);
		String remarks = null;
		StringBuilder sb = new StringBuilder();
		//为表头教学活动类型加上单位
		for(Dict d:teachTypes){
			remarks = org.apache.commons.lang3.StringUtils.trimToNull(d.getRemarks());
			if(remarks != null){
				String unit = DictUtils.getValue(remarks, "unit");
				if(unit != null ){
					if(d.getLabel().indexOf("（")>-1){
						String a=d.getLabel().substring(d.getLabel().indexOf("（")+1,d.getLabel().indexOf("）"));
						sb.append(a+"<br/>"+d.getLabel().substring(0,d.getLabel().indexOf("（")));
					}else{
						sb.append(d.getLabel());
					}
					sb.append("/"+unit);
					d.setLabel(sb.toString());
					sb.setLength(0);
				}
			}
		}
		tpTeachActive.setTeachType(null);
		tpTeachActive.setStatus(ConstantEnum.AUDIT_PASSED.getCode());
		Map<String, Map<String,Object>> listMap = tpTeachActiveService.statisticTeachType(tpTeachActive);
		request.setAttribute("listMap",listMap);
		request.setAttribute("teachTypes",teachTypes);
		request.setAttribute("selectedTeachTypes",tpTeachActive.getTeachTypeValues());
		return "modules/teach/statisticTeachTypePage";
	}

	/**
	 * 按类型统计出一段时间内每个科室的开展的某个教学活动的学时或次数
	 * @param tpTeachActive
	 * @param request
	 * @param response
	 * @return
	 * @throws Exception
	 */
	@RequestMapping(value = "/statisticSingleTeachType")
	public String statisticSingleTeachType(TpTeachActive tpTeachActive, HttpServletRequest request, HttpServletResponse response) throws Exception {
		List<Dict> dicts = DictUtils.getDictListByIds("teach_type", tpTeachActive.getTeachType());
		//没有选择教学活动类型时，默认选择第一个
		if(dicts.isEmpty() && dicts.size() > 1){
			tpTeachActive.setTeachType(dicts.get(0).getValue());
		}
		String remarks = dicts.get(0).getRemarks();
		tpTeachActive.setStatus(ConstantEnum.AUDIT_PASSED.getCode());
		//查询某个教学活动类型下各科室的参与总数
		List<Map<String, Object>> listMap = tpTeachActiveService.statisticSingleTeachType(tpTeachActive);
		if(listMap != null && !listMap.isEmpty()){
			List<Object> departmentNameList = new ArrayList<>(listMap.size());
			List<Object> totalList = new ArrayList<>(listMap.size());
			for(Map<String,Object> m:listMap){
				departmentNameList.add(m.get("departmentName"));
				totalList.add(m.get("total"));
			}
			request.setAttribute("departmentNameList",departmentNameList);
			request.setAttribute("totalList",totalList);
			request.setAttribute("maxTotal",listMap.get(0).get("total"));
			request.setAttribute("departmentNameListStr",org.apache.commons.lang3.StringUtils.join(departmentNameList,","));
			request.setAttribute("totalListStr", org.apache.commons.lang3.StringUtils.join(totalList,","));
		}
		request.setAttribute("unit",remarks != null ? DictUtils.getValue(remarks, "unit") : "");
		return "modules/teach/statisticSingleTeachType";
	}

	/*private void getCustomTitle(Model model,String teachTypes){
		String href = "/teach/tpTeachActive?teachTypes=" + teachTypes;
		List<String> menuTitle = menuDao.getMenuCustomTitle(href);
		if(!menuTitle.isEmpty()){
			Gson gson = new Gson();
			Map<String, String> map = gson.fromJson(menuTitle.get(0).replaceAll("&quot;","\""), Map.class);
			map.remove("menu_remark");
			model.addAttribute("custom_title", gson.toJson(map));
		}
	}*/
}